import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import org.junit.jupiter.api.Test;

public class WebSocketServer {

    private int port;

    public WebSocketServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new WebSocketServerInitializer());

            Channel ch = b.bind(port).sync().channel();

            System.out.println("WebSocket server started at port " + port + " awaiting connections...");

            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private static class WebSocketServerInitializer extends ChannelInitializer<Channel> {
        @Override
        protected void initChannel(Channel ch) {
            ch.pipeline().addLast(new HttpServerCodec());
            WebSocketServerProtocolConfig config = WebSocketServerProtocolConfig
                    .newBuilder()
//                    .websocketPath("/websocket")
                    .websocketPath("/websocket/x?a=1")
                    .allowExtensions(true)
                    .build();
            ch.pipeline().addLast(new WebSocketServerProtocolHandler(config));
            ch.pipeline().addLast(new WebSocketFrameHandler());
        }
    }

    private static class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            super.channelRegistered(ctx);
            System.out.println("channelRegistered。。。");
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            super.channelActive(ctx);
            System.out.println("channelActive。。。");
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            super.channelInactive(ctx);
            System.out.println("channelInactive。。。");
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
            if (frame instanceof TextWebSocketFrame) {
                TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
                System.out.println("Received text frame: " + textFrame.text());
                ctx.channel().writeAndFlush(new TextWebSocketFrame(textFrame.text()));
            } else if (frame instanceof BinaryWebSocketFrame) {
                BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
                System.out.println("Received binary frame");
                ctx.channel().writeAndFlush(new BinaryWebSocketFrame(binaryFrame.content().retain()));
            } else if (frame instanceof PongWebSocketFrame) {
                System.out.println("Received pong frame");
            } else if (frame instanceof CloseWebSocketFrame) {
                System.out.println("Received closing frame");
                ctx.close();
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }

    public static void main(String[] args) throws Exception{
        int port = 8080;
        new WebSocketServer(port).start();
    }

}